package com.icode.gulimall.search.sevice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.icode.common.to.es.SkuEsModel;
import com.icode.common.utils.R;
import com.icode.gulimall.search.config.GulimallElastcSearchConfig;
import com.icode.gulimall.search.constant.EsConstant;
import com.icode.gulimall.search.feign.ProductFeignService;
import com.icode.gulimall.search.sevice.MallSearchService;
import com.icode.gulimall.search.vo.AttrResponseVo;
import com.icode.gulimall.search.vo.BrandVo;
import com.icode.gulimall.search.vo.SearchParam;
import com.icode.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-17 18:21
 */

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient client;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        //1、准备检索请求、动态构建查询需要的DSL语句
        SearchRequest searchRequest = buildSearchRequest(param);
        SearchResult searchResult = null;
        try {
            //2、执行检索请求
            SearchResponse search = client.search(searchRequest, GulimallElastcSearchConfig.COMMON_OPTIONS);
            searchResult = buildSearchResult(search, param);
            //3、分析响应数据封装成我们需要的格式
        } catch (IOException e) {
            e.getMessage();
        }
        return searchResult;
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult searchResult = new SearchResult();
        ArrayList<SkuEsModel> skuEsModels = new ArrayList<>();
        SearchHits hits = response.getHits();
        SearchHit[] searchHits = hits.getHits();

        //封装List<SkuEsModel> products;
        if (searchHits != null && searchHits.length > 0) {
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                SkuEsModel model = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = searchHit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.fragments()[0].string();
                    model.setSkuTitle(string);
                }
                skuEsModels.add(model);
            }
            searchResult.setProducts(skuEsModels);
        }

        //封装List<AttrVo> attrs聚合
        List<SearchResult.AttrVo> attrs = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        ParsedNested attr_agg = aggregations.get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrBucket = attr_id_agg.getBuckets();
        if (!CollectionUtils.isEmpty(attrBucket)) {
            for (Terms.Bucket bucket : attrBucket) {
                //得到属性的Id
                Long attrId = (Long) bucket.getKey();
                ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
                ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
                //得到属性的name
                String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();

                //得到属性的values
                List<? extends Terms.Bucket> attrValueBuckets = attr_value_agg.getBuckets();

                List<String> attrValue = attrValueBuckets.stream().map(attrValueBucket -> {
                    String attrVal = attrValueBucket.getKeyAsString();
                    return attrVal;
                }).collect(Collectors.toList());

                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                attrVo.setAttrId(attrId);
                attrVo.setAttrName(attrName);
                attrVo.setAttrValue(attrValue);
                attrs.add(attrVo);
            }
        }
        searchResult.setAttrs(attrs);


        //封装List<BrandVo> brands聚合
        List<SearchResult.BrandVo> brands = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brandBucket = brand_agg.getBuckets();
        if (!CollectionUtils.isEmpty(brandBucket)) {
            for (Terms.Bucket bucket : brandBucket) {
                Long brandId = (Long) bucket.getKey();
                ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
                ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
                String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
                String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
                SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
                brandVo.setBrandId(brandId);
                brandVo.setBrandImg(brandImg);
                brandVo.setBrandName(brandName);
                brands.add(brandVo);
            }
        }
        searchResult.setBrands(brands);


        //封装List<CatalogVo> catalogs聚合
        List<SearchResult.CatalogVo> catalogs = new ArrayList<>();
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> catalogBuckets = catalog_agg.getBuckets();
        if (!CollectionUtils.isEmpty(catalogBuckets)) {
            for (Terms.Bucket bucket : catalogBuckets) {
                Long catalogId = (Long) bucket.getKey();
                ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
                SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
                catalogVo.setCatalogId(catalogId);
                catalogVo.setCatalogName(catalogName);
                catalogs.add(catalogVo);
            }
        }
        searchResult.setCatalogs(catalogs);


        //设置当前页码数
        searchResult.setPageNum(param.getPageNum());
        //设置总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);
        //设置总页码数
        Integer totalPage = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : (int) total / EsConstant.PRODUCT_PAGESIZE + 1;
        searchResult.setTotalPages(totalPage);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPage; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);

        //6、构建面包屑导航
        //属性面包屑
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResult.NavVo> navVos = new ArrayList<>();
            for (String attr : param.getAttrs()) {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                searchResult.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {

                    //如果远程调用失败就用attrId当做面包屑
                    // TODO: 2020/12/26  优化回显
                    navVo.setNavName(s[0]);
                }
                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String replace = replaceQueryString(attr, "attrs", param);
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                navVos.add(navVo);
            }
            searchResult.setNavs(navVos);
        }

        //品牌面包屑
        if (!CollectionUtils.isEmpty(param.getBrandIds())) {
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            List<SearchResult.NavVo> navs = searchResult.getNavs();
            navVo.setNavName("品牌");

            R r = productFeignService.brandInfo(param.getBrandIds());
            if (r.getCode() == 0) {
                List<BrandVo> brandVos = r.getData("brands", new TypeReference<List<BrandVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String replace = null;
                for (BrandVo brandVo : brandVos) {
                    buffer.append(brandVo.getName() + ";");
                    replace = replaceQueryString(brandVo.getBrandId().toString(), "brandIds", param);
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);
            }
            navs.add(navVo);
        }

        return searchResult;
    }

    private String replaceQueryString(String value, String key, SearchParam param) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+", "%20");  //浏览器对空格的编码和Java不一样，差异化处理
            encode = encode.replace("%28", "(");
            encode = encode.replace("%29", ")");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // TODO: 2020/12/26 url优化
        encode = param.get_queryString().replace("&" + key + "=" + encode, "");
        return encode;
    }

    /**
     * 准备检索请求
     *
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建DSL语句

        // 查询 过滤按照属性、分类、品牌、价格区间、库存
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //1.1模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword()))
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        //1.2 三级分类过滤
        if (param.getCatalogId() != null)
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalogId()));
        //1.2 品牌过滤
        if (!CollectionUtils.isEmpty(param.getBrandIds())) {
            //去重
            List<Long> brandIds = param.getBrandIds();
            Set<Long> set = new HashSet<>(brandIds);
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", set));
        }

        //1.2 属性过滤
        if (!CollectionUtils.isEmpty(param.getAttrs())) {
            for (String item : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = item.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个都必须生成一个nested查询
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }
        }

        //1.2 是否拥有库存过滤
        if (param.getHasStock() != null)
            //有无库存都查
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));

        //1.2 按照价格区间过滤
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] priceRange = param.getSkuPrice().split("_");
            if (priceRange.length == 2)
                rangeQuery.from(priceRange[0]).to(priceRange[1]);   //  x < skuPrice < y
            else if (param.getSkuPrice().startsWith("_"))
                rangeQuery.to(priceRange[0]); // skuPrice < x
            else
                rangeQuery.from(priceRange[0]); // x < skuPrice
            boolQueryBuilder.filter(rangeQuery);
        }

        //排序
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        //封装所有的查询条件
        sourceBuilder.query(boolQueryBuilder);

        //分页
        int from = (param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE;
        sourceBuilder.from(from).size(EsConstant.PRODUCT_PAGESIZE);
        //高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle")
                    .preTags("<b style='color:red'>")
                    .postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        //聚合分析  brand_agg  catalog_agg  attr_agg

        //品牌聚合  brand_agg
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(20);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //分类聚合  catalog_agg
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //属性聚合  attr_agg
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(1);
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));

        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);

        String s = sourceBuilder.toString();
        System.out.println(s);
        SearchRequest searchRequest = new SearchRequest(
                new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return searchRequest;
    }
}
